﻿using System;

namespace IGS.Core.Systems
{
    public class Body : IInteractable
    {
        public double Mass { get; private set; }
        public Vector Position { get; set; }
        public Vector Velocity { get; set; }
        public Vector Acceleration { get; set; }

        public double KineticEnergy
        {
            get { return 0.5 * Mass * Velocity.Length * Velocity.Length; }
        }

        public double PotentialEnergy { get; set; }

        public Vector LastPosition { get; private set; }

        public Vector LastVelocity { get; private set; }

        public Vector LastAcceleration { get; private set; }

        public Body(double mass, Vector position, Vector velocity)
        {
            Mass = mass;
            Position = position;
            Velocity = velocity;
            LastPosition = Position;
            LastVelocity = Velocity;
        }

        public void Pairwise(IInteractable other)
        {
            var dr = this.Position - other.Position;
            var r = dr.Length;
            var r3 = r * r * r;

            this.PotentialEnergy -= other.Mass / r;
            other.PotentialEnergy -= this.Mass / r;

            this.Acceleration = -(other.Mass / r3) * dr;
            other.Acceleration = +(this.Mass / r3) * dr;
        }

        public void Reset()
        {
            Acceleration = new Vector(0, 0, 0);
            PotentialEnergy = 0.0;
        }

        public void EndStep()
        {
            LastPosition = Position;
            LastVelocity = Velocity;
            LastAcceleration = Acceleration;
        }

        public override string ToString()
        {
            return String.Format("{0} {1} {2}", Mass, Position, Velocity);
        }
    }
}